<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    chartNameData: {
      type: Array,
      required: true
    },
    chartData: {
      type: Array,
      required: true
    },
    titleName: {
      type: String,
      default: 'pieChart'
    },
    name: {
      type: String,
      default: '饼图'
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartNameData: {
      deep: true,
      handler(val) {
        this.setOptions(this.titleName, val, this.name, this.chartData)
      }
    },
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(this.titleName, this.chartNameData, this.name, val)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.titleName, this.chartNameData, this.name, this.chartData)
    },
    setOptions(titleName, chartNameData, name, chartData) {
      this.chart.setOption({
        title: {
          text: titleName,
          x: 'center',
          y: 0,
          textStyle: {
            fontSize: 15
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          left: 'center',
          bottom: '10',
          data: chartNameData
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{a|{b}：{d}%}\n{hr|}',
          rich: {
            hr: {
              backgroundColor: 't',
              borderRadius: 3,
              width: 3,
              height: 3,
              padding: [3, 3, 0, 3]
            },
            a: {
              padding: [-30, 15, -20, 15]
            }
          }
        },
        series: [
          {
            name: name,
            type: 'pie',
            center: ['50%', '50%'],
            radius: ['24%', '45%'],
            data: chartData,
            animationEasing: 'cubicInOut',
            animationDuration: 2600
          }
        ]
      })
    }
  }
}
</script>
